package com.lagou.boot;

import com.alibaba.fastjson.JSON;
import com.lagou.proto.RpcResponse;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;


public class NettyServerEncoder extends MessageToByteEncoder<RpcResponse> {


    protected void encode(ChannelHandlerContext channelHandlerContext, RpcResponse rpcResponse, ByteBuf out) throws Exception {
        try {

            String requestId = rpcResponse.getRequestId();
            Object result = rpcResponse.getResult();
            byte[] resultBytes = JSON.toJSONBytes(result);

            //请求id的长度
            int requestIdLength = requestId.getBytes().length;
            int resultLength = resultBytes.length;

            //总长度
            out.writeInt(resultLength + requestIdLength + 8);
            //请求id的长度
            out.writeInt(requestIdLength);
            //请求id
            out.writeBytes(requestId.getBytes());
            //结果长度
            out.writeInt(resultLength);
            //结果
            out.writeBytes(resultBytes);

        } catch (Exception e) {
            e.printStackTrace();
            channelHandlerContext.channel().close();
        }
    }
}
